package com.lfh.easyagent.agent.controller;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;

import java.util.Arrays;

public class Main {
    public static GenerationResult callWithMessage(String content) throws ApiException, NoApiKeyException, InputRequiredException {
        Generation gen = new Generation();
        Message systemMsg = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content("You are a helpful assistant.")
                .build();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content(content)
                .build();
        GenerationParam param = GenerationParam.builder()
                .model("qwen-turbo")
                .messages(Arrays.asList(systemMsg, userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .build();
        return gen.call(param);
    }

    public static void main(String[] args) {
        try {
            String baseContent = """
                    ### 背景 ###
                    你是一个sql编写大师。
                    ### 目的 ###
                    输入一个mysql的建表语句，你能输出对应的PostgreSQL建表语句，且输出推理转化过程
                    ### 实例 ###
                    输入：CREATE TABLE IF NOT EXISTS `fe_data_collect_alert_rule` (
                           `id` bigint(20) NOT NULL AUTO_INCREMENT,
                           `data_collect_id` bigint(20) DEFAULT NULL COMMENT '表单数据id',
                           `alert_threshold` double DEFAULT NULL COMMENT '预警值',
                           `alarm_threshold` double DEFAULT NULL COMMENT '报警值',
                           `identify_event` int(4) DEFAULT '0' COMMENT '是否开始事件识别，0：否，1：是',
                           `sustain_time` int(11) DEFAULT NULL COMMENT '报警持续时间',
                           `probability` int(4) DEFAULT NULL COMMENT '报警有效值的概率',
                           `case_class_id` bigint(20) DEFAULT NULL COMMENT '事件类型id',
                           `repeated_time` int(11) DEFAULT NULL COMMENT '重复生成时间',
                           `pushed_time` datetime DEFAULT NULL COMMENT '上传推送事件时间',
                           `create_user_id` bigint(20) DEFAULT NULL COMMENT '创建人Id',
                           `gmt_create` datetime DEFAULT NULL COMMENT '创建时间',
                           `modified_user_id` bigint(20) DEFAULT NULL COMMENT '修改者id',
                           `gmt_modified` datetime DEFAULT NULL COMMENT '修改时间',
                           `is_deleted` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否删除（ 0：未删除  1：已删除）',
                           PRIMARY KEY (`id`)
                       ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='预警规则';
                    输出：DO $$
                       BEGIN IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'fe_data_collect_alert_rule') THEN
                       CREATE
                           SEQUENCE "public"."fe_data_collect_alert_rule_id_seq"
                           INCREMENT BY 1
                           MINVALUE 1
                           MAXVALUE 9223372036854775807
                           START 1
                            CACHE 1
                            NO CYCLE;
                       CREATE TABLE "public"."fe_data_collect_alert_rule"
                       (
                           "id" bigint  NOT NULL DEFAULT nextval('fe_data_collect_alert_rule_id_seq'::regclass),
                           "data_collect_id" int8,
                           "alert_threshold" float8,
                           "alarm_threshold" float8,
                           "identify_event" int4 DEFAULT 0,
                           "sustain_time" int4,
                           "probability" int4,
                           "case_class_id" int8,
                           "repeated_time" int4,
                           "pushed_time" DATETIME,
                           "create_user_id" BIGINT,
                           "gmt_create" DATETIME,
                           "modified_user_id" BIGINT,
                           "gmt_modified" DATETIME,
                           "is_deleted" TINYINT DEFAULT 0,
                           PRIMARY KEY ("id")
                       )
                           WITH (oids = false);
                       COMMENT ON TABLE "public"."fe_data_collect_alert_rule" IS '预警规则';
                       COMMENT ON COLUMN "public"."fe_data_collect_alert_rule"."data_collect_id" IS '表单数据id';
                       COMMENT ON COLUMN "public"."fe_data_collect_alert_rule"."alert_threshold" IS '预警值';
                       COMMENT ON COLUMN "public"."fe_data_collect_alert_rule"."alarm_threshold" IS '报警值';
                       COMMENT ON COLUMN "public"."fe_data_collect_alert_rule"."identify_event" IS '是否开始事件识别，0：否，1：是';
                       COMMENT ON COLUMN "public"."fe_data_collect_alert_rule"."sustain_time" IS '报警持续时间';
                       COMMENT ON COLUMN "public"."fe_data_collect_alert_rule"."probability" IS '报警有效值的概率';
                       COMMENT ON COLUMN "public"."fe_data_collect_alert_rule"."case_class_id" IS '事件类型id';
                       COMMENT ON COLUMN "public"."fe_data_collect_alert_rule"."repeated_time" IS '重复生成时间';
                       COMMENT ON COLUMN "public"."fe_data_collect_alert_rule"."pushed_time" IS '上传推送事件时间';
                       COMMENT ON COLUMN "public"."fe_data_collect_alert_rule"."create_user_id" IS '创建人Id';
                       COMMENT ON COLUMN "public"."fe_data_collect_alert_rule"."gmt_create" IS '创建时间';
                       COMMENT ON COLUMN "public"."fe_data_collect_alert_rule"."modified_user_id" IS '修改者id';
                       COMMENT ON COLUMN "public"."fe_data_collect_alert_rule"."gmt_modified" IS '修改时间';
                       COMMENT ON COLUMN "public"."fe_data_collect_alert_rule"."is_deleted" IS '是否删除（ 0：未删除  1：已删除）';
                       END IF;
                       END;
                       $$;
                     ### 提问 ###
                    """;

            String sql = """
                    CREATE TABLE AllDataTypes (
                        id BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '自增主键',
                        tinyIntColumn TINYINT(4) COMMENT 'TINYINT 类型',
                        smallIntColumn SMALLINT COMMENT 'SMALLINT 类型',
                        mediumIntColumn MEDIUMINT COMMENT 'MEDIUMINT 类型',
                        intColumn INT(11) COMMENT 'INT 类型',
                        bigIntColumn BIGINT COMMENT 'BIGINT 类型',
                        floatColumn FLOAT COMMENT 'FLOAT 类型',
                        doubleColumn DOUBLE COMMENT 'DOUBLE 类型',
                        decimalColumn DECIMAL(10, 2) COMMENT 'DECIMAL 类型',
                        charColumn CHAR(10) COMMENT 'CHAR 类型',
                        varcharColumn VARCHAR(255) COMMENT 'VARCHAR 类型',
                        textColumn TEXT COMMENT 'TEXT 类型',
                        tinyTextColumn TINYTEXT COMMENT 'TINYTEXT 类型',
                        mediumTextColumn MEDIUMTEXT COMMENT 'MEDIUMTEXT 类型',
                        longTextColumn LONGTEXT COMMENT 'LONGTEXT 类型',
                        dateColumn DATE COMMENT 'DATE 类型',
                        timeColumn TIME COMMENT 'TIME 类型',
                        dateTimeColumn DATETIME COMMENT 'DATETIME 类型',
                        timeStampColumn TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT 'TIMESTAMP 类型',
                        yearColumn YEAR COMMENT 'YEAR 类型',
                        enumColumn ENUM('value1', 'value2', 'value3') COMMENT 'ENUM 类型',
                        setColumn SET('value1', 'value2', 'value3') COMMENT 'SET 类型',
                        binaryColumn BINARY(16) COMMENT 'BINARY 类型',
                        varbinaryColumn VARBINARY(16) COMMENT 'VARBINARY 类型',
                        blobColumn BLOB COMMENT 'BLOB 类型',
                        tinyBlobColumn TINYBLOB COMMENT 'TINYBLOB 类型',
                        mediumBlobColumn MEDIUMBLOB COMMENT 'MEDIUMBLOB 类型',
                        longBlobColumn LONGBLOB COMMENT 'LONGBLOB 类型',
                        PRIMARY KEY (id)
                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
                    """;

            GenerationResult result = callWithMessage(baseContent + sql);
            System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent());
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            // 使用日志框架记录异常信息
            System.err.println("An error occurred while calling the generation service: " + e.getMessage());
        }
        System.exit(0);
    }
}